
/**
* 构建树
* @param {Array} menuList
* @param {null|string} parentId
*/
export const builderTree = (menuList: any, parentId = null) => {
  const menuTreeList: any[] = []
  menuList.forEach((menu: any) => {
    if (menu.parentId === parentId) {
      const menuItem = {
        ...menu,
        children: builderTree(menuList, menu.id)
      }
      menuTreeList.push(menuItem)
    }
  })
  return menuTreeList
}


// 根据菜单数据构建菜单树
export const builderMenuTree = (menuList: any, menuAll: any) => {
  const menuAllMap: any = {}
  menuAll.forEach((menu: any) => {
    menuAllMap[menu.id] = menu
  })
  const parentList: any = []
  menuList.forEach((menu: any) => {
    const parent = menuAllMap[menu.parentId]
    if (parent) {
      parentList.push(parent)
    }
  })
  const menuMap = new Map()
  
  parentList.concat(menuList).forEach((menu: any) => {
    menuMap.set(menu.id, menu)
  })
  const menuResult = Array.from(menuMap.values())  
  return builderTree(menuResult)
}




// 修改元素样式
export const setCssVar = (prop: string, val: any, dom = document.documentElement) => {
  dom.style.setProperty(prop, val)
}

/**
 * @param str 需要转驼峰的下划线字符串
 * @returns 字符串驼峰
 */
export const underlineToHump = (str: string): string => {
  if (!str) return ''
  return str.replace(/\-(\w)/g, (_, letter: string) => {
    return letter.toUpperCase()
  })
}

// 深度克隆
export const deepClone = (obj: any) => {
  let result: any;
  if (Object.prototype.toString.call(obj) === '[object Object]') {
    result = {};
    for (const key in obj) {
      result[key] = deepClone(obj[key]);
    }
  } else if (Array.isArray(obj)) {
    result = [];
    for (let i = 0; i < obj.length; i++) {
      result[i] = deepClone(obj[i]);
    }
  } else {
    result = obj;
  }
  return result;
}


// 删除对象属性
export const omit = (obj: any, key: any) => {
  const newObj = deepClone(obj)
  delete newObj[key]
  return newObj
}


// 防抖查询
export const debounce = (fn: Function, delay: number = 500) => {
  let timer: any = null
  return (...args: any) => {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fn(...args)
    }, delay)
  }
}